package leetcode.jianzhioffer;

import java.util.*;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-28 16:51
 **/
public class JianZhiOffer32III{

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offer(root);
        //存储每层的元素
        List<Integer> temp = null;
        //存储临时节点
        TreeNode node = null;
        //存储当前是第几行
        int row = 1;
        while (!deque.isEmpty()) {
            //记录当前层元素个数
            int size = deque.size();
            temp = new ArrayList();
            for (int i = 0; i < size; i++) {
                node = deque.poll();
                temp.add(node.val);
                if (node.left != null) {
                    deque.offer(node.left);
                }
                if (node.right != null) {
                    deque.offer(node.right);
                }
            }
            if (row % 2 == 0) {
                Collections.reverse(temp);
                list.add(temp);
            } else {
                list.add(temp);
            }
        }
        return list;
    }

}

/*class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}*/
